package com.leyou.search.service.impl;

import com.leyou.common.dto.PageDTO;
import com.leyou.common.dto.SkuDTO;
import com.leyou.common.dto.SpecParamDTO;
import com.leyou.common.dto.SpuDTO;
import com.leyou.item.client.ItemClient;

import com.leyou.search.pojo.Goods;
import com.leyou.search.respository.GoodsRepository;
import com.leyou.search.service.IndexService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class IndexServiceImpl implements IndexService {

    @Autowired
    private ItemClient itemClient;

    @Autowired
    private GoodsRepository goodsRepository;


    //把spuDTO转换为Goods
    @Override
    public Goods buildGoods(SpuDTO spuDTO) {


        // 1.自动补全的提示字段
        List<String> suggestion = new ArrayList<>(
                Arrays.asList(StringUtils.split(spuDTO.getCategoryName(), "/")));
        suggestion.add(spuDTO.getName());
        suggestion.add(spuDTO.getBrandName());

        //根据spuId查询对应的sku集合
        List<SkuDTO> skuDTOS = this.itemClient.querySkuBySpuId(spuDTO.getId());


        Goods goods = new Goods();
        BeanUtils.copyProperties(spuDTO, goods);


        //title，spuTitle，分类，品牌，中英名参照

        //TODO 中英名 思考设计
        // a/b/c=>a b c
        String categoryName = spuDTO.getCategoryName().replaceAll("/", " ");

        String newTitle = spuDTO.getTitle()+" "+categoryName+" "+spuDTO.getBrandName();

        goods.setTitle(newTitle);

        //categoryId
        goods.setCategoryId(spuDTO.getCid3());

        //image，sku的图片"http://tp1.jpg"
        goods.setImage(StringUtils.substringBefore(skuDTOS.get(0).getImages(),","));

        //prices，sku价格
        //sold，当前spu下所有的sku的销量集合

        Set<Long> skuPrices = new HashSet<>();

        long sold = 0;
        for (SkuDTO skuDTO : skuDTOS) {
            skuPrices.add(skuDTO.getPrice());
            sold += skuDTO.getSold();
        }

        goods.setPrices(skuPrices);

        goods.setSold(sold);


        //suggestion
        goods.setSuggestion(suggestion);

        //specs 当前spu（goods）的所有的可搜索规格参数，以及其对应的值
        //由于一个商品有多个可搜索规格参数所以数据结构是list，规格参数以及对应的值以map形式存储
        List<Map<String, Object>> specs = new ArrayList<>();

        //1,找到当前商品对应的所有的可搜索规格参数

        List<SpecParamDTO> specParamDTOS = this.itemClient.queryParams(spuDTO.getId(), true);

        specParamDTOS.forEach(specParamDTO -> {
            Map<String,Object> specMap = new HashMap<>(2);
            //key就是规格参数的名称
            specMap.put("name",specParamDTO.getName());
            //value
            specMap.put("value",chooseSegment(specParamDTO));
            specs.add(specMap);
        });


        goods.setSpecs(specs);

        return goods;
    }

    @Override
    public void saveGoodsById(Long spuId) {
        //添加索引

        SpuDTO spuDTOPageDTO = this.itemClient.pageQuery(null, null, spuId, null, null, null).getItems().get(0);
        Goods goods = buildGoods(spuDTOPageDTO);

        this.goodsRepository.save(goods);
    }

    @Override
    public void deleteGoodsById(Long spuId) {
        this.goodsRepository.deleteById(spuId);
    }


    private Object chooseSegment(SpecParamDTO p) {
        Object value = p.getValue();
        if (value == null || StringUtils.isBlank(value.toString())) {
            return "其它";
        }
        if (!p.getNumeric() || StringUtils.isBlank(p.getSegments()) || value instanceof Collection) {
            return value;
        }
        double val = parseDouble(value.toString());
        String result = "其它";
        // 保存数值段
        for (String segment : p.getSegments().split(",")) {
            String[] segs = segment.split("-");
            // 获取数值范围
            double begin = parseDouble(segs[0]);
            double end = Double.MAX_VALUE;
            if (segs.length == 2) {
                end = parseDouble(segs[1]);
            }
            // 判断是否在范围内
            if (val >= begin && val < end) {
                if (segs.length == 1) {
                    result = segs[0] + p.getUnit() + "以上";
                } else if (begin == 0) {
                    result = segs[1] + p.getUnit() + "以下";
                } else {
                    result = segment + p.getUnit();
                }
                break;
            }
        }
        return result;
    }

    private double parseDouble(String str) {
        try {
            return Double.parseDouble(str);
        } catch (Exception e) {
            return 0;
        }
    }




    @Override
    public void loadData() {

        //删除索引库
        try {
            Boolean deleteIndex = this.goodsRepository.deleteIndex();
        } catch (Exception e) {

        }

        //创建索引库
        this.goodsRepository.createIndex("{\n" +
                "  \"settings\": {\n" +
                "    \"analysis\": {\n" +
                "      \"analyzer\": {\n" +
                "        \"my_pinyin\": {\n" +
                "          \"tokenizer\": \"ik_smart\",\n" +
                "          \"filter\": [\n" +
                "            \"py\"\n" +
                "          ]\n" +
                "        }\n" +
                "      },\n" +
                "      \"filter\": {\n" +
                "        \"py\": {\n" +
                "\t\t  \"type\": \"pinyin\",\n" +
                "          \"keep_full_pinyin\": true,\n" +
                "          \"keep_joined_full_pinyin\": true,\n" +
                "          \"keep_original\": true,\n" +
                "          \"limit_first_letter_length\": 16,\n" +
                "          \"remove_duplicated_term\": true\n" +
                "        }\n" +
                "      }\n" +
                "    }\n" +
                "  },\n" +
                "  \"mappings\": {\n" +
                "    \"properties\": {\n" +
                "      \"id\": {\n" +
                "        \"type\": \"keyword\"\n" +
                "      },\n" +
                "      \"suggestion\": {\n" +
                "        \"type\": \"completion\",\n" +
                "        \"analyzer\": \"my_pinyin\",\n" +
                "        \"search_analyzer\": \"ik_smart\"\n" +
                "      },\n" +
                "      \"title\":{\n" +
                "        \"type\": \"text\",\n" +
                "        \"analyzer\": \"my_pinyin\",\n" +
                "        \"search_analyzer\": \"ik_smart\"\n" +
                "      },\n" +
                "      \"image\":{\n" +
                "        \"type\": \"keyword\",\n" +
                "        \"index\": false\n" +
                "      },\n" +
                "      \"updateTime\":{\n" +
                "        \"type\": \"date\"\n" +
                "      },\n" +
                "      \"specs\":{\n" +
                "        \"type\": \"nested\",\n" +
                "        \"properties\": {\n" +
                "          \"name\":{\"type\": \"keyword\" },\n" +
                "          \"value\":{\"type\": \"keyword\" }\n" +
                "        }\n" +
                "      }\n" +
                "    }\n" +
                "  }\n" +
                "}");


        int page = 1;
        //死循环查询所有的商品，没查到，或者所有的页信息展示完成了再停止
        while (true) {
            PageDTO<SpuDTO> spuDTOPageDTO =
                    this.itemClient.pageQuery(page, 50, null, null, null, null);

            //第一页就没有，停止
            if (page > spuDTOPageDTO.getTotalPage()) {
                break;
            }

            List<Goods> goodsList = spuDTOPageDTO
                    .getItems()
                    .stream()
                    .map(this::buildGoods)
                    .collect(Collectors.toList());


            this.goodsRepository.saveAll(goodsList);


            //查询完毕停止
            page++;
            if (page > spuDTOPageDTO.getTotalPage()) {

                System.out.println("商品数据倒入完成");
                break;
            }
        }
    }
    public void tongBu(Long spuId,Boolean saleable){
        if(saleable){
            //添加索引
            SpuDTO spuDTOPageDTO = this.itemClient.pageQuery(null, null, spuId, null, null, null).getItems().get(0);
            Goods goods = buildGoods(spuDTOPageDTO);
            this.goodsRepository.save(goods);
        }else{//删除索引
            this.goodsRepository.deleteById(spuId);
        }
    }
}
